<?php

/**
 * 系统加密方法
 *
 * @param string $data
 *            要加密的字符串
 * @param string $key
 *            加密密钥
 * @param int $expire
 *            过期时间 单位 秒
 * @return string
 */
function hencrypt($data, $key = '', $expire = 0)
{
    $key = md5(empty ($key) ? 'niucloud' : $key);

    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time() : 0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }
    return str_replace(array(
        '+',
        '/',
        '='
    ), array(
        '-',
        '_',
        ''
    ), base64_encode($str));
}

/**
 * 系统解密方法
 *
 * @param string $data
 *            要解密的字符串 （必须是encrypt方法加密的字符串）
 * @param string $key
 *            加密密钥
 * @return string
 */
function hdecrypt($data, $key = '')
{
    $key = md5(empty ($key) ? 'niucloud' : $key);
    $data = str_replace(array(
        '-',
        '_'
    ), array(
        '+',
        '/'
    ), $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);

    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}



/**
 * 数据签名认证
 */
function data_auth_sign($data)
{
    // 数据类型检测
    if (!is_array($data)) {
        $data = (array) $data;
    }
    ksort($data); // 排序
    $code = http_build_query($data); // url编码并生成query字符串
    $sign = sha1($code); // 生成签名
    return $sign;
}

/**
 * 重写md5加密方式
 *
 * @param unknown $str
 * @return string
 */
function data_md5($str)
{
    return '' === $str ? '' : md5(md5($str) . 'NiuCloud');
}


function remote_api(string $remote_uri, array $remote_arr, $method = 'POST')
{
    $res = httpClient($remote_uri, $remote_arr, $method, true);

    if ($res['code'] != 200) {
        return $res;
    }
    return $res['data'];
}


function httpClient(string $remote_uri,array $remote_arr,$method = 'POST',bool $is_sync = false)
{
    $key = env('ACCESS_SECRET', 'f250c494-832e-78ba-b43d-a27ce1bf3c1b');
    $access_key = env('ACCESS_KEY', '7614bc75efd95b032f9d43064ad38b01');
    $uri = env('REMOTE_HTTP', 'http://dte.dev.bjjieao.top/dte/open');
    $url = $uri . $remote_uri;
    $data = [
        'sign_timestamp' => time(),
        'sign_guid' => Illuminate\Support\Str::random(32),
        'sign_app_id' => $access_key];

    $data = array_merge($data, $remote_arr);
    $sign = get_sign($data, $key);
    $data['sign'] = $sign;
    if ($is_sync) {

        $response = curl_post($url, $data);

        $result = json_decode($response['data'], true);
        $code = $response['code'];
        if ($code != 200) {
            return ['code' =>$code, 'message' =>$result];
        }
        return ['code' => $code, 'message' => '请求成功', 'data' => $result];
    }
}



function curl_post($url , $data=array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['data'=>$output,'code'=>$httpCode];
}


function get_sign($params, $sign_key)
{
    //按字典序排序参数
    ksort($params);
    //$code = http_build_query($params);
    $array = [];
    foreach ($params as $key => $val){
        $val = is_array($val) ? json_encode($val) : $val;
        $array[] = $key . '=' . $val;
    }
    $code = implode('&',$array);
    //拼接密钥
    $code .= '&sign_key=' . $sign_key . 'jieao';

    //MD5加密
    $code = md5($code);
    //所有字符转为大写
    $result = strtoupper($code);
    return $result;
}

/**
 * 数据分组
 * @param $arr
 * @param $key
 * @return array
 */
function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}

function ngrok_url($routeName, $parameters = [])
{
    // 开发环境，并且配置了 NGROK_URL local
    if(app()->environment('production') && $url = config('app.ngrok_url')) {
        // route() 函数第三个参数代表是否绝对路径
        return $url.route($routeName, $parameters, false);
    }

    return route($routeName, $parameters);
}
